package com.ztx.jpaTest;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "JPA_CUSTOMER")
@Getter
@Setter
@Cacheable
@NamedQuery(name = "testNamedQuery",query= "From Customer c where c.id = ?")
public class Customer {

    public Customer() {
    }

    public Customer(String lastName, int age) {
        super();
        this.lastName = lastName;
        this.age = age;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "ID_GENERATOR")
    @TableGenerator(
            name = "ID_GENERATOR",
            table = "jpa_id_generator",
            pkColumnName = "PK_NAME",
            pkColumnValue = "CUSTOMER_ID",
            valueColumnName = "PK_VALUE",
            allocationSize = 1
    )
    private Integer id;

    @Column(name = "LAST_NAME", length = 50, nullable = false)
    private String lastName;

    private String email;

    private int age;

    @Temporal(TemporalType.DATE)
    private Date birth;

    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;

    /**
     * 使用@OneToMany来映射1-N
     * 使用@JoinColumn来映射外键列的名称
     * 可以使用@OneToMany的fetch属性来修改默认属性
     * 可以通过修改@OneToMany的cascade属性来修改默认删除策略
     * 注意：若在1的一端的@OneToMany中使用mappedBy属性，则@OneToMany端就不能再使用@JoinColumn属性了
     */
    @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.REMOVE},mappedBy = "customer")
    // @JoinColumn(name = "CUSTOMER_ID")
    private Set<Order> orders = new HashSet<>();

    @Transient
    public String getInfo() {
        return "lastName:" + lastName + ",email:" + email;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                ", birth=" + birth +
                ", createTime=" + createTime +
                ", orders=" + orders +
                '}';
    }
}
